package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Handler;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.novaplayer.LetvMediaPlayerControl;

/**
 * 处理全屏播放时，手势拖动快进、快退，
 * 以及手势调节音量和亮度的操作
 */
public class VideoPlayerGestureHandle {
	private final String TAG = "VideoPlayerGestureHandle";
	
	/**
	 * 最大拖动时间 2分钟
	 */
	private final static int MAXSEEKTIME = 2 * 60 * 1000;
	/**
	 * 最大系统音量
	 */
	private final static int VOLUME_MAX = 1500 ;
	
	private final String BRIGHTNESS = "brightness";
  	private final String VOLUME = "volume";
  	private final String FORWARD_IMAGEVIEW = "forward";
  	private final String BACKWARD_IMAGEVIEW = "backward";
  	private final String GESTUREGUIDE = "gestureguide";
  	private final String GESTUREGUIDE_INDEX = "gestureguideindex";
	/**
	 * 手势滑动时的起始X坐标
	 */
    private float mStartXPoint;
    /**
	 * 手势滑动时的起始Y坐标
	 */
    private float mStartYPoint;
    
    private Handler mHandler ; 
    private Activity mActivity;
    /**
	 * 全屏播放页面布局
	 */
    private View mFullScreenLayout;
    /**
     * 播放器实例，处理seekTo操作
     */
    private LetvMediaPlayerControl mPlayerController;
    /**
     * 屏幕宽度
     */
    private int mWindowWidth ;
    /**
     * 屏幕高度
     */
    private int mWindowHeight;
    /**
     * 左右滑屏
     */
    private boolean mSlideLeftAndRight;
    /**
     * 上下滑屏
     */
    private boolean mSlideUpAndDown;
    /**
     * 当前的屏幕亮度
     */
    private float mCurrentBrightness = -1f;
    /**
     * 当前的音量值
     */
    private int mCurrentVolume = -1;
    /**
     * 当前的播放时间
     */
    private int mCurrentPosition;
    
    /**
     * 音频管理器，用于调节手机音量
     */
    private AudioManager mAudioManager;
    /**
     * 显示手势拖动时的文字
     */
    private TextView mGestureDragTextView;
    /**
     * 显示手势拖动时的图片
     */
	private ImageView mGestureImageView;
    /**
     * 手势拖动时用到的弹窗
     */
	public PopupWindow mGesturePopupWindow;
	/**
     * 手势引导时用到的弹窗
     */
	public PopupWindow mGestureGuidePopupWindow;
	/**
     * 手势拖动时显示什么图片，快进、快退、音量或者亮度图片
     */
	private String mGestureImageViewFlag;
	
//	private VideoPlayerFragment mVideoPlayerFragment;
	
	private Bitmap mGestureGuideBitmap;
	
	private PlayMediaController mediaController;
	
	private SharedPreferences gestureGuidePreferences;
	
    public VideoPlayerGestureHandle(Activity activity, Handler handler,PlayMediaController mediaController,View layout){
    	mActivity = activity;
    	mHandler = handler;
    	this.mediaController = mediaController;
    	mFullScreenLayout = layout;
    	mWindowWidth = Utils.getWidthPixels(mActivity);
    	mWindowHeight = Utils.getHeightPixels(mActivity);
    	
    	initGestureView();
    }

	public View getmFullScreenLayout() {
		return mFullScreenLayout;
	}

	public void setmFullScreenLayout(View mFullScreenLayout) {
		this.mFullScreenLayout = mFullScreenLayout;
	}

	/**
	 * 初始化手势拖动时用到的图片和文字背景
	 */
	private void initGestureView() {
		if(null == mActivity){
			return ;
		}
		LayoutInflater layoutInflater = mActivity.getLayoutInflater();
		if(null == layoutInflater){
			return ;
		}
		
		View gestureView = layoutInflater.inflate(R.layout.player_gesture_drag, null);
		if(null != gestureView){
			mGestureDragTextView = (TextView)gestureView.findViewById(R.id.gesture_textview);
			mGestureImageView = (ImageView)gestureView.findViewById(R.id.gesture_imageview);
			mGesturePopupWindow = new PopupWindow(gestureView, FrameLayout.LayoutParams.WRAP_CONTENT,
					FrameLayout.LayoutParams.WRAP_CONTENT);
		}
	}
    
    /**
     * 处理手势滑动的相关操作
     * ACTION_DOWN 和 ACTION_UP事件只会执行一次，
     * @param event:滑动事件
     */
	public void handleGestureSlide(MotionEvent event, LetvMediaPlayerControl player){
		if(null == event || null == mHandler || null == player){
			 return ;
		}
		
		this.mPlayerController = player;
		
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			 mStartXPoint = event.getX(); 
			 mStartYPoint = event.getY();
			 initGestureData();
		}
		else if(event.getAction() == MotionEvent.ACTION_MOVE){
			float endXPoint = event.getX(); //手势滑动时的结束X坐标
			float endYPoint = event.getY(); //手势滑动时的结束Y坐标
			if(Math.abs(mStartXPoint - endXPoint) >= Math.abs(mStartYPoint - endYPoint) &&  mSlideLeftAndRight
					&& Math.abs(mStartXPoint - endXPoint) >= 90) {//50是个概数，满足一定的滑动距离才进入手势滑动状态
				if (mediaController.mIsPrepared) {
//					mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
					gestureBackAndForword(mStartXPoint,endXPoint);
				}
				
			}else if(Math.abs(mStartXPoint - endXPoint) < Math.abs(mStartYPoint - endYPoint) 
					&& mSlideUpAndDown
					&& Math.abs(mStartYPoint - endYPoint) >= 90){
//				mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
				gestureUpAndDown(mStartYPoint, endYPoint);
			}
		}
		else if (event.getAction() == MotionEvent.ACTION_UP){
			LogUtils.i(TAG,"***** in event.getAction() == MotionEvent.ACTION_UP *****");
//			//销毁手势引导页弹窗
//			if(null != mGestureGuidePopupWindow && mGestureGuidePopupWindow.isShowing()){
//				destroyGestureGuide();
//			}
			//销毁手势弹窗
			if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
				LogUtils.i(TAG,"***** in MotionEvent.ACTION_UP before sendMessage*****");
				mHandler.removeMessages(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW);
				mHandler.sendEmptyMessageDelayed(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW,
						Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW_TIME);
			}else{
//				fragment.fullScreenControllShow();
			}
		}
	}
	
	/**
	 * 初始化手势滑动的初始值
	 */
	private void initGestureData(){
		if(null == mActivity || null == mPlayerController){
			return ;
		}
		if(null == mAudioManager){
		    mAudioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE);
		}
		mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
		mCurrentPosition = mPlayerController.getCurrentPosition();
		mSlideUpAndDown = true;//ACTION_DOWN时，将两个标志位都置为true，根据第一次滑动时哪个方向的偏移量大，分别进行左右滑屏或者上下滑屏
		mSlideLeftAndRight = true;
	}
	
	/**
	 * 手势快进和快退
	 */
	private void gestureBackAndForword(float startX, float endX){
		mSlideUpAndDown = false;
		if(mWindowWidth > 0){
			float percent = (endX -startX) / mWindowWidth;
			gestureSeekTo(percent);
		}
		
	}
	/**
	 * 手势调节音量和亮度
	 */
	private void gestureUpAndDown(float startY,float endY){
	   mSlideLeftAndRight = false;
	   float percent = (startY - endY) / (2 * mWindowHeight / 3);// 2/3的屏幕拖动，要完成音量或者屏幕亮度从0%-100%的变化
	   if(mStartXPoint >= (mWindowWidth / 2)){//滑屏发生在右半屏，处理音量变化
		   gestureVolumeHandle(percent);
	   }else{
		   gestureBrightnessHandle(percent);
	   }
	}
	
	/**
	 * 处理手势seekto操作 
	 */
	private void gestureSeekTo(float percent){
		if(null == mPlayerController){
			return ;
		}
		
		int positionIndex = (int)(percent * MAXSEEKTIME) ;
		if(positionIndex > MAXSEEKTIME){
			positionIndex = MAXSEEKTIME;
		}else if(positionIndex < -MAXSEEKTIME){
			positionIndex = -MAXSEEKTIME;
		}
		
		int destPosition = mCurrentPosition + positionIndex;
		int duration = mPlayerController.getDuration();
		if(destPosition >= duration){
			destPosition = duration;
		}else if(destPosition <= 0){
			destPosition = 0;
		}
		
		mPlayerController.seekTo(destPosition);
		if(null != mediaController){
			mediaController.refreshPlaySeekBar();
		}
		
		if(percent >= 0){
			mGestureImageViewFlag = FORWARD_IMAGEVIEW;
		}else{
			mGestureImageViewFlag = BACKWARD_IMAGEVIEW;
		}
		int position = mPlayerController.getCurrentPosition();
		String html="<html><body><font color=\"#aabb00\">颜色1</body></html>";  
		Html.fromHtml(html);
		showGestureTimeAndVolume(mGestureImageViewFlag,
				PlayerUtils.toStringTime(position), 
				"/"+PlayerUtils.toStringTime(duration));
//		if(null != mVideoPlayerFragment) {
//			mVideoPlayerFragment.mSmallScreenPlayOrPause.setClickable(false);
//			mVideoPlayerFragment.mFullScreenPlayOrPause.setClickable(false);
//		}
	}
	
	/**
	 *  处理屏幕亮度操作
	 */
	private void gestureBrightnessHandle(float percent){
		if(mCurrentBrightness < 0){
			mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
			if(mCurrentBrightness <= 0.00f)
				mCurrentBrightness = 0.50f;
			if(mCurrentBrightness < 0.01f)
				mCurrentBrightness = 0.009f;
		}
		
		mGestureImageViewFlag = BRIGHTNESS;
		WindowManager.LayoutParams lParam = mActivity.getWindow().getAttributes();
		lParam.screenBrightness = mCurrentBrightness + percent;
		if (lParam.screenBrightness > 1.0f){
			lParam.screenBrightness = 1.0f;	
		}else if (lParam.screenBrightness < 0.01f){
			lParam.screenBrightness = 0.009f;
		}
			
		mActivity.getWindow().setAttributes(lParam);
		showGestureTimeAndVolume(mGestureImageViewFlag,(int)(lParam.screenBrightness * 100)  + "%",null);
	}
	
	/**
	 *  手势音量操作
	 */
	private void gestureVolumeHandle(float percent){
		if(mCurrentVolume == -1 && null != mAudioManager){
			mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			if(mCurrentVolume < 0){
				mCurrentVolume = 0;
			}
		}
		
		mGestureImageViewFlag = VOLUME;
		int volumeIndex = (int)(percent * VOLUME_MAX) + mCurrentVolume * 100; //用于匹配进度条可以从0%-100%变化
//		mVideoPlayerFragment.setCurrentVolume(volumeIndex);
		mediaController.setCurrentVolume(volumeIndex);
		int volumeShowOnText = 100 * volumeIndex / VOLUME_MAX;
		if(volumeShowOnText > 100)
			volumeShowOnText = 100;
		else if(volumeShowOnText < 0)
			volumeShowOnText = 0;

		volumeIndex = volumeIndex / 100;
		if (volumeIndex > 15)
			volumeIndex = 15;
		else if (volumeIndex < 0)
			volumeIndex = 0;
		showGestureTimeAndVolume(mGestureImageViewFlag,volumeShowOnText + "%",null);
	}
	
	/**
	 * 显示手势拖动时的弹窗 
	 */
	private void showGestureTimeAndVolume(String imageViewBg,String textViewShowed,String forwardText){
		if(null == mGestureDragTextView || null == mGestureImageView
				|| null == mGesturePopupWindow){
			return ;
		}	
		
		if(imageViewBg == BRIGHTNESS){
			mGestureImageView.setImageResource(R.drawable.gesture_brightness);
			mGestureDragTextView.setText(textViewShowed);
		}else if(imageViewBg == VOLUME){
			mGestureImageView.setImageResource(R.drawable.gesture_volume);
			mGestureDragTextView.setText(textViewShowed);
		}else if(imageViewBg == FORWARD_IMAGEVIEW){
			mGestureImageView.setImageResource(R.drawable.gesture_forward);
			String html="<html><body><font color=\"#1283f6\">"+textViewShowed+"</font><font>"+forwardText+"</font></body></html>";  
			mGestureDragTextView.setText(Html.fromHtml(html));
		}else if(imageViewBg == BACKWARD_IMAGEVIEW){
			mGestureImageView.setImageResource(R.drawable.gesture_backward);
			String html="<html><body><font color=\"#1283f6\">"+textViewShowed+"</font><font>"+forwardText+"</font></body></html>";    
			mGestureDragTextView.setText(Html.fromHtml(html));
		}
		if(null != mFullScreenLayout){
			int[] location = new int[2];
			mFullScreenLayout.getLocationOnScreen(location);
			View view = mGesturePopupWindow.getContentView();
			int w =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
			int h =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
			view.measure(w,h);
			int height= view.getMeasuredHeight();
			int width=view.getMeasuredWidth();
			mGesturePopupWindow.showAtLocation(mFullScreenLayout,Gravity.NO_GRAVITY, location[0] + mFullScreenLayout.getWidth() / 2 - width / 2,
					location[1] + mFullScreenLayout.getHeight() / 2 - height / 2);
		}
	}

	public void dismissGestureGuideView() {
		if (mGestureGuidePopupWindow != null && mGestureGuidePopupWindow.isShowing()) {
			mGestureGuidePopupWindow.dismiss();
		}
	}

	/**
	 * 显示手势引导页,只在第一次展示全屏时出现
	 */
	public void showGestureGuideView(boolean isFullScreen){
		if(null == mActivity || mActivity.isFinishing()){
			return ;
		}
		gestureGuidePreferences = mActivity.
				getSharedPreferences(GESTUREGUIDE, Context.MODE_PRIVATE);
		if(null == gestureGuidePreferences){
			return ;
		}
		if (MoviesConstant.isFirstPlayVideo) {
			MoviesConstant.isFirstPlayVideo = gestureGuidePreferences.getBoolean(GESTUREGUIDE_INDEX, true);
		}
		if(MoviesConstant.isFirstPlayVideo){
			LayoutInflater layoutInflater = mActivity.getLayoutInflater();
			if(null == layoutInflater){
				return ;
			}
			View gestureGuidView = layoutInflater.inflate(R.layout.gesture_guide_index,null);
			TextView voiceTextView = (TextView) gestureGuidView.findViewById(R.id.tv_change_voice);
			TextView speedTextView = (TextView) gestureGuidView.findViewById(R.id.tv_change_speed);
			ImageView voiceImageView = (ImageView) gestureGuidView.findViewById(R.id.gesture_ex1);
			ImageView voiceImageView1 = (ImageView) gestureGuidView.findViewById(R.id.gesture_ex2);
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)voiceTextView.getLayoutParams();
			params.setMargins(mFullScreenLayout.getWidth() / 8 , 0, 0, mFullScreenLayout.getHeight() / 6);
			voiceTextView.setLayoutParams(params);
			RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams)speedTextView.getLayoutParams();
			params2.setMargins(0 , 0, mFullScreenLayout.getWidth() / 8, mFullScreenLayout.getHeight() / 6);
			speedTextView.setLayoutParams(params2);
			RelativeLayout.LayoutParams paramsImage = (RelativeLayout.LayoutParams)voiceImageView.getLayoutParams();
			paramsImage.height = mFullScreenLayout.getWidth() / 3;
			paramsImage.width = mFullScreenLayout.getWidth() / 6;
			paramsImage.setMargins((int)(5.0 / 36 * mFullScreenLayout.getWidth()) , 0, 0, 0);
			voiceImageView.setLayoutParams(paramsImage);
			RelativeLayout.LayoutParams paramsImage1 = (RelativeLayout.LayoutParams)voiceImageView1.getLayoutParams();
			paramsImage1.height = (int)(mFullScreenLayout.getWidth() * 135.0 / 540);
			paramsImage1.width = (int)(mFullScreenLayout.getWidth() * 13.0 / 54);
			paramsImage1.setMargins(0 , 0, (int)(mFullScreenLayout.getWidth() * 1.0 / 12), 0);
			voiceImageView1.setLayoutParams(paramsImage1);

			if(null == mGestureGuidePopupWindow){
				mGestureGuidePopupWindow = new PopupWindow(gestureGuidView, mFullScreenLayout.getWidth(),
						mFullScreenLayout.getHeight());
			} else {
				if (mGestureGuidePopupWindow.isShowing()) {
					mGestureGuidePopupWindow.dismiss();
				}
				mGestureGuidePopupWindow = new PopupWindow(gestureGuidView, mFullScreenLayout.getWidth(),
						mFullScreenLayout.getHeight());
			}
			if(null != mGestureGuidePopupWindow && null != mFullScreenLayout
					&& mFullScreenLayout.isShown()){
				try {
					mGestureGuidePopupWindow.update();
					int[] location = new int[2];
					mFullScreenLayout.getLocationOnScreen(location);
					mGestureGuidePopupWindow.showAtLocation(mFullScreenLayout,Gravity.NO_GRAVITY, location[0], location[1]);
					gestureGuidView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							SharedPreferences.Editor mEditor = gestureGuidePreferences.edit();
							if(mEditor != null){
								mEditor.putBoolean(GESTUREGUIDE_INDEX, false);
								mEditor.commit();
								MoviesConstant.isFirstPlayVideo = false;
								//销毁手势引导页弹窗
								if(null != mGestureGuidePopupWindow && mGestureGuidePopupWindow.isShowing()){
									destroyGestureGuide();
								}
							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 销毁手势弹窗
	 */
	public void dismissGesturePopupWindow(){
		if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
			mGesturePopupWindow.dismiss();
		}
	}

	/**
	 * 判断该popupwindow是否展示
	 */
	public boolean isGesturePopupWindowShow(){
		boolean isShow = false;
		if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
			isShow = true;
		}
		return isShow;
	}

	/**
	 * 判断手势引导页是否展示
	 * @return
     */
	public boolean isGestureGuidePopupWindowShow(){
		boolean isShow = false;
		if(null != mGestureGuidePopupWindow && mGestureGuidePopupWindow.isShowing()){
			isShow = true;
		}
		return isShow;
	}
	
	/**
	 * 销毁手势引导页弹窗
	 */
	public void destroyGestureGuide(){
	   if(null != mGestureGuidePopupWindow && 
			   mGestureGuidePopupWindow.isShowing()){
		   mGestureGuidePopupWindow.dismiss();
		   mGestureGuidePopupWindow = null;
	   }
	   if(null != mGestureGuideBitmap && !mGestureGuideBitmap.isRecycled()){
		   mGestureGuideBitmap.recycle();
		   mGestureGuideBitmap = null;
	   }
	}
	
	public void destroyResource() {
		mAudioManager = null;
		mGestureDragTextView = null;
		mGestureImageView = null;
		mGesturePopupWindow = null;
		mPlayerController = null;
		mActivity = null;
	}
	
}
